const logger = require('log4js').getLogger()

module.exports = (req, res) => {
    require('../util/service').handlePost(req, res, (reqObj, resolve) => {
        if (!reqObj.bill) {
            resolve({
                result: -1,
                msg: '缺少bill'
            })
            return
        }
        if (req.session.customer.claimBillFailTimes > 5) {
            logger.error('[' + __filename + ':' + __line + '] over times');
            resolve({
                result: -1,
                msg: '系统错误'
            })
            return
        }
        const mongoMng = require('../mng/mongoMng')
        if (!mongoMng.db) {
            log('未连接mongo')
            resolve({
                result: -1,
                msg: '系统错误'
            })
            return;
        }
        mongoMng.db.collection('bill').find({
            $or: [{
                taobaoTradeParentId: reqObj.bill
            }, {
                orderId: parseInt(reqObj.bill)
            }, {
                tradeParentId: reqObj.bill
            }],
            customer_phone: null,
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err);
                resolve({
                    result: -1,
                    msg: '系统错误'
                })
                return;
            }
            if (result.length > 0) {
                mongoMng.db.collection('bill').update({
                    $or: [{
                        taobaoTradeParentId: reqObj.bill
                    }, {
                        orderId: parseInt(reqObj.bill)
                    }, {
                        tradeParentId: reqObj.bill
                    }],
                    customer_phone: null,
                }, {
                    $set: {
                        customer_phone: req.session.customer.phone
                    }
                }, {
                    multi: true
                }, (err, result) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err);
                        return;
                    }
                    resolve({
                        result: 1
                    })
                })
            } else {
                req.session.customer.claimBillFailTimes = (req.session.customer.claimBillFailTimes || 0) + 1
                resolve({
                    result: -1,
                    msg: '找不到订单'
                })
            }
        })
    })
}